<template>
  <view>
    <view class="staffing-header-wrapper">
      <view class="staffing-title">选择员工</view>
      <template v-if="staff.length > 0">
        <scroll-view class="scroll-view_H" scroll-x="true" scroll-left="120">
          <view
            id="demo1"
            class="scroll-view-item_H"
            v-for="(item, index) in staff"
            :key="item.userId"
          >
            <view @tap="removeStaff(index)">
              <image
                class="slot-image"
                :src="item.userImage"
                mode="widthFix"
              ></image>
              <view class="slot-user">{{ item.userName }}</view>
            </view>
          </view>
        </scroll-view>
      </template>
      <view class="footer-wrapper">
        <image
          class="slot-image"
          src="../../static/staffing-add.png"
          mode="widthFix"
          @tap="selectEmployee"
        ></image>
        <image
          class="slot-image"
          src="../../static/staffing-remove.png"
          mode="widthFix"
          @tap="removeEmployees"
        ></image>
      </view>
    </view>
    <uni-list :border="false">
      <uni-list-item
        thumb-size="lg"
        title="选择权限范围"
        link
        @click="onClick"
      ></uni-list-item>
    </uni-list>
    <template v-if="authorities.length > 0">
      <uni-list style="margin-top: 30upx" :border="false">
        <block v-for="(item, index) in authorities" :key="index">
          <template v-if="item.isActive !== false">
            <uni-list-item
              :thumb="item.userImage"
              thumb-size="lg"
              :title="item.userName"
            >
              <template slot="footer">
                <button class="footer-remove-btn" @click="removeAuth(index)">
                  删除
                </button>
              </template></uni-list-item
            >
          </template>
        </block>
      </uni-list>
    </template>
    <view class="null-content"></view>
    <view class="footer-btn">
      <view class="footer-mark"
        >注意：添加人员配置，请点击下面的保存按钮，否则不生效</view
      >
      <view class="to-add" @tap="toSave">保存</view>
    </view>
  </view>
</template>

<script>
import uniList from "../../components/uni-list/uni-list";
import uniListItem from "../../components/uni-list-item/uni-list-item";
import { savePower, savePowerSource } from "../../common/service.js";
export default {
  components: {
    uniList,
    uniListItem,
  },
  data() {
    return {
      loginInfo: {},
      callbackItems: [], // 上一页带回的已选项
      callbackStaff: [], // 上一页带回的已选项
      authorities: [],
      staff: [],
    };
  },
  onLoad: function (e) {
    if (e.loginInfo) {
      this.loginInfo = JSON.parse(e.loginInfo);
    }
  },
  onShow() {
    if (this.callbackItems.length > 0) {
      this.authorities = this.unique(
        this.authorities.concat(this.callbackItems)
      );
    }
    if (this.callbackStaff.length > 0) {
      this.staff = this.unique(this.staff.concat(this.callbackStaff));
    }
    if (this.loginInfo) {
      this.loginInfo = this.loginInfo;
    }
  },
  methods: {
    /**
     * 根据 id 进行数组去重
     * @param {array} origin 原始数组
     */
    unique(origin) {
      let temp = {};
      return origin
        .reverse()
        .filter((item) =>
          item.userId in temp ? false : (temp[item.userId] = true)
        );
    },
    toSave() {
      if (this.staff.length <= 0 || this.authorities.length <= 0) {
        uni.showToast({
          title: "员工或授权范围不能为空，请选择员工和选择权限范围",
        });
        return;
      }

      uni.showLoading({
        title: "保存中",
      });
      let powerDeptList = [];
      let powerUserList = [];

      if (this.authorities.length > 0) {
        this.authorities.forEach((auth) => {
          if (this.staff.length > 0) {
            this.staff.forEach((staff) => {
              if (auth.type == "department") {
                powerDeptList.push({
                  powerModule: this.loginInfo.powerModule,
                  parentUserId: this.loginInfo.parentUserId, // 父级授权人
                  toPowerId: staff.userId, //   授权对象
                  powerDeptId: auth.userId,
                });
              } else if (auth.type == "employee") {
                powerUserList.push({
                  powerModule: this.loginInfo.powerModule,
                  parentUserId: this.loginInfo.parentUserId, // 父级授权人
                  toPowerId: staff.userId, //   授权对象
                  powerUserId: auth.userId, // 被授权的对象id（删除部门权限此项传空）
                });
              }
            });
          }
        });
      }
      const data = {
        powerDeptList: powerDeptList,
        powerUserList: powerUserList,
      };

      savePower(
        data,
        (res) => {
          if (res && res.data && res.data.code == 200) {
            uni.showToast({
              type: "success",
              title: "保存成功",
              duration: 2000,
              mask: true,
            });
            setTimeout(() => {
              this.authorities = [];
              uni.navigateBack({
                delta: 1,
              });

              const values = [];
              this.staff.map((s) => {
                values.push(s.userId);
              });
              savePowerSource(
                { userNames: values.join(",") },
                (res) => {
                  console.log(res.data);
                },
                (err) => {
                  console.log(err);
                }
              );
            }, 2000);
          } else {
            uni.showToast({
              title: "保存权限失败",
              duration: 2000,
            });
          }
        },
        (err) => {
          uni.showToast({
            title: "操作失败",
            duration: 2000,
          });
        }
      );
    },
    removeEmployees() {
      if (this.staff.length > 0) {
        this.staff = [];
      }
    },
    removeStaff(index) {
      if (this.staff.length > 0) {
        this.staff.splice(index, 1);
      }
    },
    removeAuth(index) {
      if (this.authorities.length > 0) {
        this.authorities.splice(index, 1);
      }
    },
    onClick() {
      const isSelectStaff = false;
      const title = "选择权限范围";
      const isJump = false;

      uni.navigateTo({
        url:
          "../selectStaff/selectStaff?isSelectStaff=" +
          JSON.stringify(isSelectStaff) +
          "&postStaff=" +
          JSON.stringify(this.authorities) +
          "&title=" +
          JSON.stringify(title) +
          "&isJump=" +
          JSON.stringify(isJump) +
          "&loginInfo=" +
          JSON.stringify(this.loginInfo),
      });
    },
    selectEmployee() {
      const isSelectStaff = true;
      const title = "选择员工";
      const isJump = false;

      uni.navigateTo({
        url:
          "../selectStaff/selectStaff?isSelectStaff=" +
          JSON.stringify(isSelectStaff) +
          "&postStaff=" +
          JSON.stringify(this.staff) +
          "&title=" +
          JSON.stringify(title) +
          "&isJump=" +
          JSON.stringify(isJump) +
          "&loginInfo=" +
          JSON.stringify(this.loginInfo),
      });
    },
  },
};
</script>

<style scope>
.staffing-title {
  margin: 33upx 22upx;
  font-size: 32upx;
  font-weight: 500;
  color: #333333;
  line-height: 36upx;
}
.scroll-view_H {
  margin-bottom: 43upx;
  white-space: nowrap;
  float: left;
  width: calc(100% - 202upx);
}
.scroll-view-item_H {
  margin: 0 17upx;
  display: inline-block;
  width: auto;
  height: 134upx;
}
.slot-image {
  width: 84upx;
  height: 84upx;
}
.slot-user {
  text-align: center;
  font-size: 28upx;
  font-weight: 500;
  color: #333333;
}
.footer-wrapper {
  margin-bottom: 43upx;
  display: flex;
  justify-content: space-around;
  float: right;
  width: 202upx;
  height: 84upx;
}
.footer-remove-btn {
  font-weight: 500;
  color: #3875c6;
  font-size: 32upx;
  background: transparent;
}
.footer-remove-btn:after {
  border: none;
}
.footer-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  background: transparent;
}
.footer-mark {
  flex: 1;
  font-size: 26upx;
  color: #fd0043;
}
.to-add {
  width: 90%;
  line-height: 100rpx;
  text-align: center;
  font-size: 30rpx;
  font-weight: bold;
  color: #ffffff;
  background: #35c260;
  border-radius: 6upx;
  margin: 30upx 0;
}
.null-content {
  height: 206upx;
}
</style>
